#pragma once
#include <QHBoxLayout>
#include <QWidget>

#include "OPeratorinter.h"
#include "page/PageElement.h"
#include "PageRelevancy.h"
#include "item/LabelItem.h"

class TitleWidget :
    public PageElement
{
    Q_OBJECT
public:
    TitleWidget(QWidget* parent) : PageElement(parent)
    {
        m_mainLayout = new QHBoxLayout(this);
        setLayout(m_mainLayout);
    }

    void addItem(QWidget *w)
    {
        m_mainLayout->insertWidget(m_mainLayout->count(), w);
        if (auto item = qobject_cast<LabelItem*>(w))
        {
            m_operatorinter.addItem(item);
        }
    }

	void comeIn() override
    {
        m_operatorinter.clearItemStat();
        PageRelevancy::getInstance()->setFocus(this);
        //m_operatorinter.selectFirstItem();
        auto item = m_operatorinter.firstItem();
        item->setSelect(true);
    }
	void esc()override
    {
        //m_operatorinter.clearItemStat();
    }
	void left()override
    {
        m_operatorinter.left();
        auto title = m_operatorinter.getSelect();
        emit signal_selectChanged(title);
    }
	void right()override
    {
        m_operatorinter.right();
        auto title = m_operatorinter.getSelect();
        emit signal_selectChanged(title);
    }
	void up()override
    {
    }
	void down()override {}

    void reComeIn() override
    {
        m_operatorinter.setSelect(m_operatorinter.getSelectIndex());
        PageRelevancy::getInstance()->setFocus(this);
    }

    void enter() override
    {
        m_operatorinter.clearItemStat();
	    if (auto item = m_operatorinter.getSelect())
	    {
            auto page = PageRelevancy::getInstance()->getRelevancyByParent(dynamic_cast<QWidget*>(item));
            if (auto widget = dynamic_cast<PageElement*>(page))
            {
                widget->comeIn();
            }
	    }
    }

    ItemBase* getFirstItem()
    {
        return m_operatorinter.firstItem();
    }

    void clearAllFocus()
    {
        m_operatorinter.clearItemStat();
    }

    signals:
        void signal_selectChanged(QWidget* title);
private:
    OPeratorinter<ItemBase> m_operatorinter;
    QHBoxLayout* m_mainLayout{ nullptr };
};

